package com.apes.fico.masterdata.gl.service;

import com.apes.fico.masterdata.gl.model.CashFlow;
import com.apes.fico.masterdata.gl.respository.CashFlowRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 功能：
 *
 * @Auther: linwz
 * @Date: 2018/8/13 10:51
 */
@Service("cashFlowService")
public class CashFlowService extends DomainService {

    @Autowired
    CashFlowRepository cashFlowRepository;

    /**
     * 保存
     * @param request
     * @return
     */
    public CashFlow save(SimpleRequest request) {
        CashFlow cashFlow = request.getO(CashFlow.class);
        return cashFlowRepository.saveAndFlush(cashFlow);
    }

    /**
     * 删除
     * @param request
     * @return
     */
    public String delete(SimpleRequest request) {
        String id = request.get("id") ;
        Integer versions = request.get("version");
        cashFlowRepository.delete(id);
        CashFlow cashFlow = request.getO(CashFlow.class);
        if (cashFlow == null) throw new RuntimeException("现金流量【"+ id +"】在系统中不存在。");
        if (cashFlow.getVersion() != versions)throw new RuntimeException("记录已更新或已删除，请重新提交！");
        return "删除成功";
    }

    /**
     * 查询
     * @param request
     * @return
     */
    public Page<CashFlow> findAll(SimpleRequest request){
        List<Map> filters = request.get("condition");
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        return cashFlowRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size"), sort));
    }
}
